#include "onnxrecognizetask.h"
#include "opencv2/opencv.hpp"
#include <QDateTime>
#include "../cnn/Yolo.h"
#include "../cnn/defectrecognizer.h"
#include <QMutex>

QMutex OnnxRecognizeTask::mutex;

OnnxRecognizeTask::OnnxRecognizeTask() {}

void OnnxRecognizeTask::run(){
    mutex.lock();
    qDebug() << "开始处理一张图像";

    int imageNum                                        = ((QVariant)parameters["content"]).toInt();
    int imageWidth                                      = ((QVariant)parameters["imageWidth"]).toInt();
    int imageHeight                                     = ((QVariant)parameters["imageHeight"]).toInt();
    int imageChannel                                    = ((QVariant)parameters["imageChannel"]).toInt();
    char* pSrcBuffer                                    = (char*)(parameters["pSrcBuffer"].value<void*>());
    char* pDestBuffer                                   = (char*)(parameters["pDestBuffer"].value<void*>());
    DefectRecognizer* pDefectRecognizer                 = (DefectRecognizer*)(parameters["pDefectRecognizer"].value<void*>());
    CameraViewWidget* pViewWidget                       = (CameraViewWidget*)(parameters["pViewWidget"].value<void*>());

    cv::Mat imageSrc(imageHeight,imageWidth,CV_8UC3);
    memcpy(imageSrc.data,pSrcBuffer,imageWidth * imageHeight * imageChannel);
    cv::Mat imageDst = imageSrc.clone();

    qint64 CurrentMEpoch1 = QDateTime::currentMSecsSinceEpoch();
    //m_objORTRecognizer.test(imageSrc);
    //std::vector<Detection> result = m_objORTRecognizer.RecognizePartsDefect(imageSrc);

    std::vector<Detection> results = pDefectRecognizer->RecognizePartsDefect(imageSrc);

    pDefectRecognizer->DrawPred(imageDst, results);
    memcpy(pDestBuffer,imageDst.data,imageWidth * imageHeight * imageChannel);

    emit finishRecognizeImage(imageNum);

    QString filename = QString("d:/test/seat/seat_yolov8n_%1.jpg").arg(imageNum);
    imwrite(filename.toStdString(), imageDst);

    qint64 CurrentMEpoch2 = QDateTime::currentMSecsSinceEpoch();
    QString elapse = QString::number(CurrentMEpoch2 - CurrentMEpoch1);
    qDebug() << "处理一张图像耗时：" << elapse << "ms";
    mutex.unlock();
}
